﻿using System;
using System.Collections;
using System.Configuration;
using System.Collections.Specialized;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Drawing;
using IronOne.SalesOne.BusinessObjects;


namespace IronOne.SalesOne.SalesOneWeb
{
    public partial class CreateMessage : SOSecurityPage
    {
        Facade.StructureFacade structureFacade = new Facade.StructureFacade();
        Facade.MessageFacade messageFacade = new Facade.MessageFacade();  

        private static string userName ;
        private static string userId;
        private static UserInformation info;
        private static int userType;
        private static int groupId;

        static List<Branch> lstBranches;
        static List<SalesOneUnit> lstUnits;
        static List<string> lstSocodes ;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                SetCredentials(ValidateUserCredentials(Request.Url.LocalPath));
                if (!IsPostBack)
                {
                    /*Get The current User*/
                    MembershipUser membershipUser = Membership.GetUser(HttpContext.Current.User.Identity.Name);
                    userName = membershipUser.UserName;
                    User user = structureFacade.GetUser(userName);
                    userId = user.UserId.ToString();

                    info = structureFacade.GetUserInformation(User.Identity.Name);
                    userType = info.UserType;

                    if (userType != 1)
                        groupId = (int)info.GroupId;
                    else
                        groupId = 0;

                    //SetDataSourceToFrom(structureFacade.GetUserTypesForUser("UserTypeId ASC", userName));
                    SetDataSourceToFrom(structureFacade.GetUserTypes("UserTypeId ASC"));
                    //string ss=(structureFacade.GetUserTypeForUser(userName).UserTypeId.ToString());
                    ddlFrom.SelectedIndex = (structureFacade.GetUserTypeForUser(userName).UserTypeId);

                    /*
                    PopulateValuesForUserType();
                    */

                    /*Sajith Code using sp*/
                    bool flag = false;

                    chkBroadcast.Enabled = false;


                    if (userType == 4)
                    {
                        //if (user.SoCode != null)
                        //{
                        //    lstSocodes = new List<string>();
                        //    lstSocodes.Add(user.SoCode);
                        //    SetDataSourceToSoCode(lstSocodes);
                        //    ddlSOCode.SelectedIndex = ddlSOCode.Items.Count - 1;
                        //    ddlSOCode.Enabled = false;
                        //}
                        //else
                        //{
                        lstSocodes = structureFacade.GetSOsInUnit(user.NodeId);
                        SetDataSourceToSoCode(lstSocodes);
                        //}
                        if (ddlSOCode.SelectedIndex == -1)
                            ddlSOCode.SelectedIndex = 0;

                        flag = true;
                    }

                    if (flag == true)
                    {
                        //ListItem item =new ListItem();
                        //item.Text=info.UnitName;
                        //item.Value=Convert.ToInt32(info.UnitId).ToString();
                        //ddlUnit.Items.Add(item);
                        lstUnits = new List<SalesOneUnit>();
                        lstUnits.Add(structureFacade.GetUnit(Convert.ToInt32(info.UnitId)));
                        SetDataSourceToUnits(lstUnits);
                        ddlUnit.SelectedIndex = ddlUnit.Items.Count - 1;
                        ddlUnit.Enabled = false;
                    }
                    else if (userType == 3)
                    {
                        lstUnits = structureFacade.GetUnitsForBranch(Convert.ToInt32(user.NodeId));
                        SetDataSourceToUnits(lstUnits);
                        ddlUnit.SelectedIndex = 0;
                        addDefaultItem(ddlSOCode);
                        
                        flag = true;
                    }

                    if (flag == true)
                    {
                        lstBranches = new List<Branch>();
                        lstBranches.Add(structureFacade.GetBranch(Convert.ToInt32(info.BranchId)));
                        SetDataSourceToBranches(lstBranches);
                        ddlBranch.SelectedIndex = ddlBranch.Items.Count - 1;
                        ddlSOCode.SelectedIndex = 0;
                        ddlBranch.Enabled = false;
                    }
                    else if (userType == 2)
                    {
                        lstBranches = structureFacade.GetBranchesForGroup(Convert.ToInt32(user.NodeId));
                        SetDataSourceToBranches(lstBranches);
                        ddlBranch.SelectedIndex = 0;
                        addDefaultItem(ddlUnit);
                        addDefaultItem(ddlSOCode);
                        flag = true;
                    }

                    if (userType == 1)
                    {
                        chkBroadcast.Enabled = true;
                        lstBranches = structureFacade.GetBranches("BranchName ASC");
                        SetDataSourceToBranches(lstBranches);
                        addDefaultItem(ddlUnit);
                        addDefaultItem(ddlSOCode);

                        ddlBranch.SelectedIndex = 0;
                    }
                }
                //lblError.ForeColor = Color.Black;
                //lblError.Text = "";
                ddlFrom.Enabled = false;
            }
            catch { MassageSummery("IIS514"); }
        }

        private void addDefaultItem(DropDownList ddl)
        {
            try
            {
                ListItem newItem = new ListItem("Select...");
                ddl.Items.Insert(0, newItem);
            }
            catch (Exception)
            {

            }

        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            try
            {
                if (ddlFrom.SelectedIndex > 0)
                {
                    bool isValid=false;

                    ManageMessages createMessage = new ManageMessages();
                    createMessage.UserId = structureFacade.GetUser(userName).UserId;
                    createMessage.Body = txtMessage.Text;
                    //createMessage.GroupId = structureFacade.GetGroup(userName).GroupId;
                    createMessage.GroupId = Convert.ToInt32(info.GroupId);
                    createMessage.FromUserTypeId = Convert.ToInt32(ddlFrom.SelectedValue);
                    createMessage.Broadcasted = chkBroadcast.Checked;

                    if (chkBroadcast.Checked)
                        isValid = true;

                    if (ddlBranch.SelectedIndex > 0)
                    {
                        if (ddlBranch.SelectedIndex == 1)
                            createMessage.Branches = lstBranches;
                        else
                        {
                            createMessage.BranchId = Convert.ToInt32(ddlBranch.SelectedValue);
                            List<Branch> lstBanch = new List<Branch>();
                            lstBanch.Add(lstBranches.Find(GetBranch));
                            createMessage.Branches = lstBanch;
                        }
                        isValid = true;
                    }
                    if (ddlUnit.SelectedIndex > 0)
                    {
                        if (ddlUnit.SelectedIndex == 1)
                            createMessage.Units = lstUnits;
                        else
                        {
                            List<SalesOneUnit> lstUnit = new List<SalesOneUnit>();
                            lstUnit.Add(lstUnits.Find(GetUnit));
                            createMessage.Units = lstUnit;
                        }
                        isValid = true;
                    }
                    if (ddlSOCode.SelectedIndex > 0)
                    {
                        if (ddlSOCode.SelectedIndex == 1)
                            createMessage.SOCodes = lstSocodes;
                        else
                        {
                            List<string> lstSoCode = new List<string>();
                            lstSoCode.Add(lstSocodes.Find(GetSOCode));
                            createMessage.SOCodes = lstSoCode;
                        }
                        isValid = true;
                    }
                    if(isValid)
                    {

                        int messageId=messageFacade.InsertMessage(createMessage);
                        //Response.Redirect("~/Messaging/SearchMessages.aspx?MessageId="+messageId.ToString());
                        MassageSummery("IIS404");
                    }
                    else
                    {
                        MassageSummery("IIS505");
                    }

                }
                else
                {
                    MassageSummery("IIS505");
                }
            }
            catch
            {
                MassageSummery("IIS502");
            }      
        }      

        public void SetDataSourceToBranches(List<Branch> branches)
        {

            try
            {
                ddlBranch.SelectedIndex = 0;
            }
            catch { ddlBranch.SelectedIndex = -1; }
            ddlBranch.Items.Clear();

            if (branches.Count > 0)
            {
                ddlBranch.DataSource = branches;
                ddlBranch.DataTextField = "BranchName";
                ddlBranch.DataValueField = "BranchID";
                ddlBranch.DataBind();
            }

            InsertDDLItems(ddlBranch, "Select...", 0);
            InsertDDLItems(ddlBranch, "All", 1);
        }

        public void SetDataSourceToUnits(List<SalesOneUnit> units)
        {
            try
            {
                ddlUnit.SelectedIndex = 0;
            }
            catch { ddlUnit.SelectedIndex = -1; }
            ddlUnit.Items.Clear();

            if (units.Count > 0)
            {
                ddlUnit.DataSource = units;
                ddlUnit.DataTextField = "Name";
                ddlUnit.DataValueField = "UnitId";
                ddlUnit.DataBind();
            }

            InsertDDLItems(ddlUnit, "Select...", 0);
            InsertDDLItems(ddlUnit, "All", 1);
        }

        public void SetDataSourceToSoCode(List<string> users)
        {
            try
            {
                ddlSOCode.SelectedIndex = 0;
            }
            catch { ddlSOCode.SelectedIndex = -1; }
            ddlSOCode.Items.Clear();

            if (users.Count > 0)
            {
                ddlSOCode.DataSource = users;
                ddlSOCode.DataBind();
            }

            InsertDDLItems(ddlSOCode, "Select...", 0);
            InsertDDLItems(ddlSOCode, "All", 1);
        }


        public void SetDataSourceToSoCode(List<User> users)
        {
            ddlSOCode.DataSource = users;
            ddlSOCode.DataTextField = "Name";
            ddlSOCode.DataValueField = "UserId";
            ddlSOCode.DataBind();

            InsertDDLItems(ddlSOCode, "Select...", 0);
            InsertDDLItems(ddlSOCode, "All", 1);
        }

        public void SetDataSourceToFrom(List<UserType> userTypes)
        {
            try
            {
                ddlBranch.SelectedIndex = 0;
            }
            catch { ddlBranch.SelectedIndex = -1; }
            ddlBranch.Items.Clear();

            if (userTypes.Count > 0)
            {
                ddlFrom.DataSource = userTypes;
                ddlFrom.DataTextField = "UserTypeName";
                ddlFrom.DataValueField = "UserTypeId";
                ddlFrom.DataBind();
            }

            InsertDDLItems(ddlFrom, "Select...", 0);
            //InsertDDLItems(ddlFrom, "All", 1);
        }

        public void InsertDDLItems(DropDownList ddl, string Text, int Position)
        {
            ListItem item = new ListItem(Text, Text);
            ddl.Items.Insert(Position, Text);
        }

        protected void chkBroadcast_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                DisableControlsForBroadcasting();
            }
            catch { MassageSummery("IIS514"); }
        }

        public void DisableControlsForBroadcasting()
        {
            if (chkBroadcast.Checked)
            {
                EnableControls(false);
            }
            else
            {
                EnableControls(true);
            }
        }

        protected void ddlUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                EnableControls(true);
                if (ddlUnit.SelectedIndex > 1)
                {
                    ddlSOCode.Items.Clear();
                    lstSocodes = structureFacade.GetSOsInUnit(int.Parse(ddlUnit.SelectedValue));
                    SetDataSourceToSoCode(lstSocodes);

                }
                else if (ddlUnit.SelectedIndex == 1)
                {
                    ddlSOCode.Enabled = false;
                    ddlSOCode.Items.Clear();
                    addDefaultItem(ddlSOCode);
                }
                else if (ddlUnit.SelectedIndex == 0)
                {
                    
                    ddlSOCode.Enabled = false;
                    ddlSOCode.Items.Clear();
                    addDefaultItem(ddlSOCode);
                    DisableControlsForUserType(userType);
                }
                DisableControlsForUserType(userType);
            }
            catch { MassageSummery("IIS514"); }
        }

        protected void ddlFrom_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                PopulateValuesForUserType();
                DisableControlsForUserType(userType);
            }
            catch { MassageSummery("IIS514"); }
        }

        public void DisableControlsForHQ()
        {
            chkBroadcast.Enabled = false;
            chkBroadcast.Checked = false;
            DisableControlsForBroadcasting();
        }

        public void EnableControls(bool enabled)
        {
            ddlBranch.Enabled = enabled;
            ddlUnit.Enabled = enabled;
            ddlSOCode.Enabled = enabled;
        }

        private bool GetBranch(Branch branch)
        {
            if (branch.BranchId == Convert.ToInt32(ddlBranch.SelectedValue))
                return true;
            else
                return false;

        }

        private bool GetUnit(SalesOneUnit unit)
        {
            if (unit.UnitId == Convert.ToInt32(ddlUnit.SelectedValue))
                return true;
            else
                return false;
        }

        private bool GetSOCode(string soCode)
        {
            if (soCode.Equals(ddlSOCode.SelectedItem.Text))
                return true;
            else
                return false;

        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Messaging/SearchMessages.aspx");
        }

        protected void ddlBranch_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                EnableControls(true);
                if (ddlBranch.SelectedIndex > 1)
                {
                    ddlUnit.Items.Clear();
                    lstUnits = structureFacade.GetUnitsInBranch(int.Parse(ddlBranch.SelectedValue));
                    SetDataSourceToUnits(lstUnits);

                    ddlSOCode.Items.Clear();
                    addDefaultItem(ddlSOCode);
                }
                else if (ddlBranch.SelectedIndex == 1)
                {
                    ddlUnit.Enabled = false;
                    ddlUnit.Items.Clear();
                    ddlSOCode.Items.Clear();
                    ddlSOCode.Enabled = false;
                    addDefaultItem(ddlUnit);
                    addDefaultItem(ddlSOCode);
                }
                else if (ddlBranch.SelectedIndex == 0)
                {
                    
                    ddlUnit.Enabled = false;
                    ddlUnit.Items.Clear();
                    ddlSOCode.Items.Clear();
                    ddlSOCode.Enabled = false;
                    addDefaultItem(ddlUnit);
                    addDefaultItem(ddlSOCode);
                    DisableControlsForUserType(userType);
                }
                DisableControlsForUserType(userType);
            }
            catch { MassageSummery("IIS514"); }
        }

        private void PopulateValuesForUserType()
        {
            if (ddlFrom.SelectedItem.Text.Equals("HQ", StringComparison.InvariantCultureIgnoreCase))
            {
                chkBroadcast.Enabled = true;
                lstBranches = structureFacade.GetBranches("BranchName ASC");
                SetDataSourceToBranches(lstBranches);
                ddlUnit.Items.Clear();
                ddlSOCode.Items.Clear();
                EnableControls(true);
            }
            /*If Group selected populate the branches according to the group*/
            else if (ddlFrom.SelectedItem.Text.Equals("Group", StringComparison.InvariantCultureIgnoreCase))
            {
                DisableControlsForHQ();
                lstBranches = structureFacade.GetBranchesForGroup(groupId);
                SetDataSourceToBranches(lstBranches);
                //populate branches
                ddlUnit.Items.Clear();
                ddlSOCode.Items.Clear();
                EnableControls(true);
            }
            /*If brnch - populate the branches according to the selected branch */
            else if (ddlFrom.SelectedItem.Text.Equals("Branch", StringComparison.InvariantCultureIgnoreCase))
            {
                DisableControlsForHQ();
                //populate units
                lstUnits = structureFacade.GetUnitsInBranch("UnitName", userName);
                SetDataSourceToUnits(lstUnits);
                ddlSOCode.Items.Clear();
                ddlBranch.Enabled = false;
            }
            /*If units then -units acoording to the .....*/
            else if (ddlFrom.SelectedItem.Text.Equals("Unit", StringComparison.InvariantCultureIgnoreCase))
            {
                lstSocodes = structureFacade.GetSOsForUser("", userName);
                SetDataSourceToSoCode(lstSocodes);
                DisableControlsForHQ();
                //populate socodes
                ddlBranch.Enabled = false;
                ddlUnit.Enabled = false;
            }
        }

        public void SetCredentials(StringCollection credential)
        {
            foreach (string item in credential)
            {
                if (item.ToLower() == "c")
                    btnCreate.Visible = true;
            }
        }

        public void DisableControlsForUserType(int userType)
        {
             bool flag = false;

             MembershipUser membershipUser = Membership.GetUser(HttpContext.Current.User.Identity.Name);
                userName = membershipUser.UserName;
                User user = structureFacade.GetUser(userName);

            if (userType == 4)
                {
                  
                    flag = true;
                }

                if (flag == true)
                {
                   
                    ddlUnit.Enabled = false;
                }
                else if (userType == 3)
                {
                   
                    flag = true;
                }

                if (flag == true)
                {
                   
                    ddlBranch.Enabled = false;
                }
                else if (userType == 2)
                {
                  
                    flag = true;
                }

                if (userType == 1)
                {
                    chkBroadcast.Enabled = true;
                   
                }
        }

        protected void ddlSOCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                DisableControlsForUserType(userType);
            }
            catch { MassageSummery("IIS514"); }
        }
    }
}
